<?php
class TopicController extends Controller
{
	public function actionIndex()
	{
		if(!isset($_GET['id']))
			throw new CHttpException(404,'invalid request');

		$tid=(int)$_GET['id'];
		$data['topic']=Topic::model()->findByPk($tid);

		if(empty($data['topic']))
			throw new CHttpException(404,'invalid request');

		$data['author']=$data['topic']->author;

		if(Yii::app()->user->isGuest || $data['author']->id!=Yii::app()->user->id)
			$data['isAuthor']=FALSE;
		else
			$data['isAuthor']=TRUE;

		$data['comment']=new Comment;
		$data['commentList']=$data['topic']->comment;

		$this->render('index',$data);	
	}

	public function actionPost()
	{
		//TODO 验证是否已加入小组
		if(isset($_GET['id']))
			$model=Topic::model()->findByPk($_GET['id']);
		else
			$model=new Topic;
		if(!isset($_GET['gid']))
			throw new CHttpException(404,'invalid request');
		$gid=(int)$_GET['gid'];
		if(Yii::app()->user->isGuest)
			$this->redirect('site/login');

		if(isset($_POST['Topic']))
		{
			$model->attributes=$_POST['Topic'];
			$model->uid=Yii::app()->user->id;
			$model->gid=$gid;
			$model->save();
			$this->redirect('index.php?r=group/visit&id='.$gid);
		}
		
		$data['topic']=$model;
		$this->render('post',$data);
	}

	public function actionDelete()
	{
		if(!isset($_GET['id']))
			throw new CHttpException(404,'invalid request');

		//TODO 验证删除权限

		$topic=Topic::model()->findByPk($_GET['id']);
		if(empty($topic))
			throw new CHttpException(404,'invalid request');

		$gid=$topic->group->id;
		if($topic->delete())
		{
			//TODO 删除评论
			$this->redirect('index.php?r=group/visit&id='.$gid);
		}
		else
			throw new CHttpException(404,'invalid request');
	}
}
?>
